package com.example.gateway_server.filter;

import cn.dev33.satoken.stp.StpUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final StringRedisTemplate redisTemplate;

    public AuthGlobalFilter(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private static final List<String> WHITE_LIST = Arrays.asList(
            "/auth-service/auth/login",
            "/auth/login",
            "/auth-service/auth/register"
//            "/user-service/user/list",
//            "/activity-service/activity/list/published"
    );

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();

        // 白名单直接放行
        if(WHITE_LIST.contains(path)) {
            return chain.filter(exchange);
        }

        // 从header获取token
        String token = request.getHeaders().getFirst("Authorization");
        if(token == null || !token.startsWith("Bearer ")) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        token = token.substring(7); // 去掉Bearer前缀


        try {
            // 直接从Redis校验token是否存在
            String redisKey = "satoken:login:token:" + token;

            // 获取用户ID (从Redis中获取)
            String userIdKey = "satoken:login:token:" + token + ":userid";
            String userId = redisTemplate.opsForValue().get(userIdKey);
            // 将用户ID添加到请求头
            ServerHttpRequest newRequest = request.mutate()
                    .header("userId", userId)
                    .build();
            if(redisKey.equals(token)){
                System.out.println("校验通过");
                return chain.filter(exchange.mutate().request(newRequest).build());
            }
            return chain.filter(exchange.mutate().request(newRequest).build());

        } catch (Exception e) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
